package com.gitee.yannzh.rune.common.util;

import org.apache.commons.beanutils2.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yann
 * @description: java bean工具类
 */
public class BeanUtil {

    /**
     * 对象浅拷贝
     *
     * @param source 目标对象
     * @param clazz  目标类型
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        try {
            T obj = clazz.newInstance();
            BeanUtils.copyProperties(obj,source);
            return obj;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * List对象浅拷贝
     *
     * @param sourceList
     * @param clazz
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> List<T> copyList(List<S> sourceList, Class<T> clazz) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        return sourceList.stream().map(e -> copy(e, clazz)).collect(Collectors.toList());
    }


}
